//
//  ProgressBar.m
//  etionUI
//
//  Created by wangjian on 1/10/13.
//
//

#import "ProgressBar.h"

@implementation CProgressBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        m_progress = 0;
        self.backgroundColor = [UIColor clearColor];
        // Initialization code
        _titleLabel = [[UILabel alloc] initWithFrame:self.bounds];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textAlignment = UITextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:14];
        [self addSubview:_titleLabel];
    }
    return self;
}

- (void)dealloc
{
    [_titleLabel release_mm];
    superdealloc_mm;
}

- (void)setProgress:(float)progress animated:(BOOL)animated
{
    if (progress > 100)
    {
        m_progress = 100;
    }
    else
    {
        m_progress = progress;
    }
    [self setNeedsDisplay];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [self drawBGView:rect];
}

- (void)drawRoundRectPath:(CGRect)rect radius:(float)radius context:(CGContextRef)context
{
    CGContextMoveToPoint(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect));
    CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMinY(rect) + radius, radius, 3 * M_PI / 2, 0, 0);
    CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMaxY(rect) - radius, radius, 0, M_PI / 2, 0);
    CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMaxY(rect) - radius, radius, M_PI / 2, M_PI, 0);
    CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect) + radius, radius, M_PI, 3 * M_PI / 2, 0);
    CGContextClosePath(context);
}

- (void)drawBGView:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    int radius = rect.size.height/2;
    if (radius >= rect.size.width/2)
    {
        return;
    }
    
    CGContextBeginPath(context);
    
    CGContextSetFillColorWithColor(context, [UIColor orangeColor].CGColor);
    [self drawRoundRectPath:rect radius:radius context:context];
    CGContextDrawPath(context, kCGPathFill);
    
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    [self drawRoundRectPath:CGRectInset(rect, rect.origin.x + 1, rect.origin.y + 1) radius:radius - 1 context:context];
    CGContextDrawPath(context, kCGPathFill);

    CGContextSetFillColorWithColor(context, [UIColor orangeColor].CGColor);
    CGRect progressRect = CGRectInset(rect, rect.origin.x + 3, rect.origin.y + 3);
    progressRect.size.width = progressRect.size.width * m_progress / 100;
    [self drawRoundRectPath:progressRect radius:radius - 3 context:context];
    CGContextDrawPath(context, kCGPathFill);
}

@end
